/*
 * @Author: c
 * @Date: 2023-11-30 08:49:17
 * @LastEditTime: 2024-01-05 22:34:03
 * @LastEditors: c
 * @Description: 
 * @FilePath: \music-web-backend\src\auth\auth.service.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import { UserVo } from 'src/core/system/user/vo/user.vo';
import { AuthVo } from './vo/auth.vo';
import { BcryptService } from 'src/common/service/bcrypt.service';
@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService
  ) { }

  async signIn(userName: string, passwd: string) {
    // const user = await this.userService.findOne(userName);

    // if (user?.password !== passwd) {
    //     throw new UnauthorizedException()
    // }
    // const payload = { sub: user.userId, username: user.username };

    // return { access_token: await this.jwtService.signAsync(payload) };
  }

  async validateUser(username: string, password: string): Promise<AuthVo> {
    const user = await this.userService.findOneByUserName(username);
    if (user && await BcryptService.compare(password, user.password)) {
      const { password, ...result } = user;
      const payload = { userId: user.id, username: user.username, roles: user.roles.map(role => role.code) };
      // return new AuthVo({ ...payload, tokenType: 'Bearer', accessToken: await this.jwtService.signAsync(payload) });
      return { ...payload, tokenType: 'Bearer', accessToken: await this.jwtService.signAsync(payload) }
    }
    return null;
  }

}
